let d1RowsLock = 0;
$NG.AllReady(function (page, { useValuesChange, useClick, useUpdateRow, useUpdateRows, useDataIndexChange }) {
  console.log("page is ready");
  console.log($NG.getPageUI());
  console.log($NG.getPageState());
  var mstform = $NG.getCmpApi("p_form_invoice_apply_m");
  var dgrid = $NG.getCmpApi("p_form_invoice_apply_d");

  const toolbar = $NG.getCmpApi("toolbar");
  const toolbar_top = $NG.getCmpApi("toolbar_top");
  const toolbar_dgrid1 = $NG.getCmpApi("toolbar_" + "p_form_invoice_apply_d");
  const toolbar_dgrid2 = $NG.getCmpApi("toolbar_" + "p_form_invoice_apply_d1");
  const toolbars = [
    { toolbar: toolbar_top, items: ["imp"] },
    { toolbar: toolbar_dgrid2, items: ["imp"] },
  ];
  toolbars.forEach(({ toolbar, items }) => {
    if (toolbar && typeof toolbar.getItem === "function") {
      items.forEach((item) => {
        const button = toolbar.getItem(item);
        if (button) {
          button.setHidden(); // 隐藏按钮
        }
      });
    }
  });

  toolbar_dgrid1.getItem("imp").setProps({ children: "引用合同清单明细" });

  if (mstform) {
    setTimeout(()=>{
        //init///////////////////////////////
        dgrid.getData().forEach((item) => {
            const fields = ["u_tdyw", "u_tdzzs_no", "u_jzfwfsd", "u_detail_addr", "u_kdbz"];
            console.log(`调试`,item.u_ssfl_no);
            if (item.u_ssfl_no == 4100) {
                $NG.updateUI((updater) => {
                    fields.forEach((field) => {
                    updater.fieldSetForm.p_form_invoice_apply_m[field].setProps({
                        required: true,
                        hidden: false,
                    });
                    });
                });
            }
        });
    },1000)
    mstformUpdateUI(mstform);
    // getEnterpriseInfoByPhid(mstform);
    getProjectInfo(mstform);
    cntMFilter();
    if (page.oType == "add") {
      getCntCount();
    }
  }
  if (dgrid) {
    dgrid1UpdateUI();
    cntDFilter();
  }
  //创建高级对象，间接实现监听字段
  // function _sum(){
  //     $NG.updateState((updater)=>{
  //         updater.data.p_form_invoice_apply_m.setProps({
  //             MyEventObject:MyEventObject._u_xfyh,
  //             MyEventObject:MyEventObject._u_gfyh,
  //         })
  //     })
  //         GetBankInfoByPhid(MyEventObject._u_gfyh?.value,'gf')
  //         GetBankInfoByPhid(MyEventObject._u_xfyh?.value, 'xf')
  // }
  // const MyEventObject = {
  //     _u_xfyh:null,
  //     _u_gfyh:null,
  //     set u_xfyh(value){
  //         this._u_xfyh = {...value}
  //        _sum()
  //     },
  //     set u_gfyh(value){
  //         console.log(`这个value`,value);
  //         this._u_gfyh = {...value}
  //         console.log(`这个value`,this._u_gfyh,this._u_xfyh);
  //         _sum()
  //     }
  // }
  //页面条件
  if (page.oType == "add" || page.oType == "edit") {
    $NG.execServer("getEpmInfoByUserID", { phid: $NG.getUser().userID }, (res) => {
      const datas = JSON.parse(res.data)[0].extendObjects;
      console.log(datas);
      //   开票申请里的发票类型改为手填20241225
      //   console.log("拿去合同号带出来的发票类型", mstform.getItem("u_invoice_type"));
      //更新UI表格
      $NG.updateState((updater) => {
        //【注意这里的表名不能为控件ID，必须要是表名】
        updater.data.p_form_invoice_apply_m.setProps({
          u_hr_apply: {
            value: datas.hem_phid,
            label: datas.hem_name,
          },
          u_dept_apply: {
            value: datas.dept_phid,
            label: datas.dept_name,
          },
        });
      });
    });
    calculationPay();
  }
  function init() {
    $NG.updateState((updater) => {
      updater.data.p_form_invoice_apply_m.setProps({
        u_invoice_dt: formatDate(new Date(), "yyyy-mm-dd"),
      });
    });
  }

  // 监听字段项目
  useValuesChange(({ args }) => {
    console.log(`监听项目字段`, args);
    cntMFilter();
    getCntCount();
    getProjectInfo(mstform);
    getLcbHkInfo()
    $NG.updateState((updater) => {
      updater.data.p_form_invoice_apply_m.setProps({
        u_cnt: {
          label: null,
          value: null,
        },
        u_cnt_no: null,
        u_cnt_amt: null,
      });
    });
  }, "p_form_invoice_apply_m.phid_pc");

  //表头字段变化逻辑BEGIN
  useValuesChange(({ args }) => {
    getCntMInfoByPhid();
    cntDFilter();
  }, "p_form_invoice_apply_m.u_cnt");

  //监听汇款差额
  useValuesChange(({ args }) => {
    const _data = args[0].u_hkkpce;

    //表头多字段设置属性
    $NG.updateUI((updater) => {
      if (Number(_data) < 0) {
        updater.form.p_form_invoice_apply_m.u_hkcesm.setProps({
          required: true, //必输
        });
      } else {
        updater.form.p_form_invoice_apply_m.u_hkcesm.setProps({
          required: false, //必输
        });
      }
    });
  }, "p_form_invoice_apply_m.u_hkkpce");

  useValuesChange(({ args }) => {
    const _data = args[0].u_srkpce;
    //表头多字段设置属性
    $NG.updateUI((updater) => {
      if (Number(_data) < 0) {
        updater.form.p_form_invoice_apply_m.u_srcesm.setProps({
          required: true, //必输
        });
      }
    });
  }, "p_form_invoice_apply_m.u_srkpce");

  useValuesChange(({ args }) => {
    console.log(`监听银行`, args);
    GetBankInfoByPhid(mstform.getItem("u_gfyh").getValue(), "gf");
  }, "p_form_invoice_apply_m.u_gfyh");

  useValuesChange(({ args }) => {
    console.log("监听红蓝类型", args);
    const isRed = args[0].u_hllx.value === "1"; // 红字为 true

    $NG.updateUI((updater) => {
      ["u_lzfpdm", "u_lzfphm", "u_hzxx"].forEach((field) => {
        updater.fieldSetForm.p_form_invoice_apply_m[field].setProps({
          disabled: isRed,
          required: !isRed,
        });
      });
    });
  }, "p_form_invoice_apply_m.u_hllx");

  if (page.oType == "add" || page.oType == "edit") {
    let _xfyh = null;
    const _xfTime = setInterval(() => {
      try {
        if (mstform.getItem("u_xfyh").getValue() !== _xfyh) {
          _xfyh = mstform.getItem("u_xfyh").getValue();
          GetBankInfoByPhid(mstform.getItem("u_xfyh").getValue(), "xf");
        }
      } catch (err) {
        clearInterval(_xfTime);
        console.log("自定义监听器报错，行号：102");
      }
    }, 1000);

    let _gfyh = null;
    const _gfTime = setInterval(() => {
      try {
        if (mstform.getItem("u_gfyh").getValue() !== _gfyh) {
          _gfyh = mstform.getItem("u_gfyh").getValue();
          GetBankInfoByPhid(mstform.getItem("u_gfyh").getValue(), "gf");
        }
      } catch (err) {
        clearInterval(_gfTime);
        console.log("自定义监听器报错，行号：115");
      }
    }, 1000);
  }

  //p_form_invoice_apply_d

  
  ///////////////////////
  useUpdateRows(({ args }) => {
    const _data = args[0];
    // 分流操作，防止并发太多
    if (d1RowsLock) {
      clearTimeout();
    }
    d1RowsLock = setTimeout(() => {
      sumAmt();let d1RowsLock = 0;
      $NG.AllReady(function (page, { useValuesChange, useClick, useUpdateRow, useUpdateRows, useDataIndexChange }) {
        console.log("page is ready");
        console.log($NG.getPageUI());
        console.log($NG.getPageState());
        var mstform = $NG.getCmpApi("p_form_invoice_apply_m");
        var dgrid = $NG.getCmpApi("p_form_invoice_apply_d");
      
        const toolbar = $NG.getCmpApi("toolbar");
        const toolbar_top = $NG.getCmpApi("toolbar_top");
        const toolbar_dgrid1 = $NG.getCmpApi("toolbar_" + "p_form_invoice_apply_d");
        const toolbar_dgrid2 = $NG.getCmpApi("toolbar_" + "p_form_invoice_apply_d1");
        const toolbars = [
          { toolbar: toolbar_top, items: ["imp"] },
          { toolbar: toolbar_dgrid2, items: ["imp"] },
        ];
        toolbars.forEach(({ toolbar, items }) => {
          if (toolbar && typeof toolbar.getItem === "function") {
            items.forEach((item) => {
              const button = toolbar.getItem(item);
              if (button) {
                button.setHidden(); // 隐藏按钮
              }
            });
          }
        });
      
        toolbar_dgrid1.getItem("imp").setProps({ children: "引用合同清单明细" });
      
        if (mstform) {
          mstformUpdateUI(mstform);
          // getEnterpriseInfoByPhid(mstform);
          getProjectInfo(mstform);
          cntMFilter();
          if (page.oType == "add") {
            getCntCount();
          }
        }
        if (dgrid) {
          dgrid1UpdateUI();
          cntDFilter();
        }
        //创建高级对象，间接实现监听字段
        // function _sum(){
        //     $NG.updateState((updater)=>{
        //         updater.data.p_form_invoice_apply_m.setProps({
        //             MyEventObject:MyEventObject._u_xfyh,
        //             MyEventObject:MyEventObject._u_gfyh,
        //         })
        //     })
        //         GetBankInfoByPhid(MyEventObject._u_gfyh?.value,'gf')
        //         GetBankInfoByPhid(MyEventObject._u_xfyh?.value, 'xf')
        // }
        // const MyEventObject = {
        //     _u_xfyh:null,
        //     _u_gfyh:null,
        //     set u_xfyh(value){
        //         this._u_xfyh = {...value}
        //        _sum()
        //     },
        //     set u_gfyh(value){
        //         console.log(`这个value`,value);
        //         this._u_gfyh = {...value}
        //         console.log(`这个value`,this._u_gfyh,this._u_xfyh);
        //         _sum()
        //     }
        // }
        //页面条件
        if (page.oType == "add" || page.oType == "edit") {
          $NG.execServer("getEpmInfoByUserID", { phid: $NG.getUser().userID }, (res) => {
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log(datas);
            //   开票申请里的发票类型改为手填20241225
            //   console.log("拿去合同号带出来的发票类型", mstform.getItem("u_invoice_type"));
            //更新UI表格
            $NG.updateState((updater) => {
              //【注意这里的表名不能为控件ID，必须要是表名】
              updater.data.p_form_invoice_apply_m.setProps({
                u_hr_apply: {
                  value: datas.hem_phid,
                  label: datas.hem_name,
                },
                u_dept_apply: {
                  value: datas.dept_phid,
                  label: datas.dept_name,
                },
              });
            });
          });
          calculationPay();
        }
        function init() {
          $NG.updateState((updater) => {
            updater.data.p_form_invoice_apply_m.setProps({
              u_invoice_dt: formatDate(new Date(), "yyyy-mm-dd"),
            });
          });
        }
      
        // 监听字段项目
        useValuesChange(({ args }) => {
          console.log(`监听项目字段`, args);
          cntMFilter();
          getCntCount();
          getLcbHkInfo()
          getProjectInfo(mstform);
          $NG.updateState((updater) => {
            updater.data.p_form_invoice_apply_m.setProps({
              u_cnt: {
                label: null,
                value: null,
              },
              u_cnt_no: null,
              u_cnt_amt: null,
            });
          });
        }, "p_form_invoice_apply_m.phid_pc");
      
        //表头字段变化逻辑BEGIN
        useValuesChange(({ args }) => {
          getCntMInfoByPhid();
          cntDFilter();
        }, "p_form_invoice_apply_m.u_cnt");
      
        //监听汇款差额
        useValuesChange(({ args }) => {
          const _data = args[0].u_hkkpce;
      
          //表头多字段设置属性
          $NG.updateUI((updater) => {
            if (Number(_data) < 0) {
              updater.form.p_form_invoice_apply_m.u_hkcesm.setProps({
                required: true, //必输
              });
            } else {
              updater.form.p_form_invoice_apply_m.u_hkcesm.setProps({
                required: false, //必输
              });
            }
          });
        }, "p_form_invoice_apply_m.u_hkkpce");
      
        useValuesChange(({ args }) => {
          const _data = args[0].u_srkpce;
          //表头多字段设置属性
          $NG.updateUI((updater) => {
            if (Number(_data) < 0) {
              updater.form.p_form_invoice_apply_m.u_srcesm.setProps({
                required: true, //必输
              });
            }
          });
        }, "p_form_invoice_apply_m.u_srkpce");
      
        useValuesChange(({ args }) => {
          console.log(`监听银行`, args);
          GetBankInfoByPhid(mstform.getItem("u_gfyh").getValue(), "gf");
        }, "p_form_invoice_apply_m.u_gfyh");
      
        useValuesChange(({ args }) => {
          console.log("监听红蓝类型", args);
          const isRed = args[0].u_hllx.value === "1"; // 红字为 true
      
          $NG.updateUI((updater) => {
            ["u_lzfpdm", "u_lzfphm", "u_hzxx"].forEach((field) => {
              updater.fieldSetForm.p_form_invoice_apply_m[field].setProps({
                disabled: isRed,
                required: !isRed,
              });
            });
          });
        }, "p_form_invoice_apply_m.u_hllx");
      
        if (page.oType == "add" || page.oType == "edit") {
          let _xfyh = null;
          const _xfTime = setInterval(() => {
            try {
              if (mstform.getItem("u_xfyh").getValue() !== _xfyh) {
                _xfyh = mstform.getItem("u_xfyh").getValue();
                GetBankInfoByPhid(mstform.getItem("u_xfyh").getValue(), "xf");
              }
            } catch (err) {
              clearInterval(_xfTime);
              console.log("自定义监听器报错，行号：102");
            }
          }, 1000);
      
          let _gfyh = null;
          const _gfTime = setInterval(() => {
            try {
              if (mstform.getItem("u_gfyh").getValue() !== _gfyh) {
                _gfyh = mstform.getItem("u_gfyh").getValue();
                GetBankInfoByPhid(mstform.getItem("u_gfyh").getValue(), "gf");
              }
            } catch (err) {
              clearInterval(_gfTime);
              console.log("自定义监听器报错，行号：115");
            }
          }, 1000);
        }
      
        //p_form_invoice_apply_d
      
        useUpdateRows(({ args }) => {
          const _data = args[0];
          // 分流操作，防止并发太多
          if (d1RowsLock) {
            clearTimeout();
          }
          d1RowsLock = setTimeout(() => {
            sumAmt();
          }, 600);
          // 默认数量为1
          // args[0].forEach((item) => {
          //   if (!item.qty || item.qty < 0) {
          //     item.qty = 1;
          //   }
          // });
      
          // 遍历明细，如果明细存在建筑服务的税收分类编码，更改主表字段属性
      
          const fields = ["u_tdyw", "u_tdzzs_no", "u_jzfwfsd", "u_detail_addr", "u_kdbz"];
          let isRequired = false;
          let filter = "itm3_tax_classcode.phid != 0"; // 默认值
      
          _data.forEach(async (item) => {
            await getSumEqInfo(mstform, item);
            dgrid.refreshView();
          });
      
          _data.forEach((item) => {
            if (item.u_ssfl_no === 4100) {
              isRequired = true;
            }
            if(!item.u_kp_remark){
              item.u_kp_remark = '无'
            }
          });
      
          if (_data.some((item) => item.u_ssfl_no === 4100)) {
            filter = "itm3_tax_classcode.phid = 4100";
          } else if (_data.some((item) => item.u_ssfl_no !== "" && item.u_ssfl_no !== null && item.u_ssfl_no !== undefined)) {
            if (args[0].u_ssfl_no !== 4100) {
              filter = "itm3_tax_classcode.phid != 4100";
            }
          }
      
          $NG.updateUI((updater) => {
            const ssflField = updater.editGrid.p_form_invoice_apply_d.u_ssfl_no;
            if (ssflField) {
              ssflField.setProps({ clientSqlFilter: filter });
            }
          });
          $NG.updateUI((updater) => {
            fields.forEach((field) => {
              updater.fieldSetForm.p_form_invoice_apply_m[field].setProps({
                required: isRequired,
                hidden: !isRequired,
              });
            });
          });
          if (!mstform.getItem("u_tdyw").getValue()) {
            mstform.getItem("u_tdyw").setValue({
              value: "E03",
              label: "建筑服务",
            });
          }
      
          dgrid.refreshView();
        }, "p_form_invoice_apply_d");
      
        //优先性设置
        // let _d_amt = 0;
        // useUpdateRow(({ args }) => {
        //   console.log(args);
        //   const record = args[0];
        //   const _data = args[0];
        //   record.u_ratee = record.u_jshj - record.amt;
        //   if (_data.u_vat_prc && _data.taxrate) {
        //     _data.prc = Number(_data.u_vat_prc) / (1 + Number(_data.taxrate));
        //   }
        //   if (_data.u_jshj && _data.taxrate) {
        //     _data.amt = Number(_data.u_jshj) / (1 + Number(_data.taxrate));
        //     _data.u_ratee = Number((_data.u_jshj / (1 + _data.taxrate)) * _data.taxrate);
        //   }
        //   dgrid.refreshView();
        // }, "p_form_invoice_apply_d");
      
        useDataIndexChange(async ({ args, instance }) => {
          console.log(`监听 u_cnt_no`);
          await getCntDInfoByPhid(mstform, args[0]);
          await getSumEqInfo(mstform, args[0]); // 等 getCntDInfoByPhid 执行完成之后再执行
          instance.updateRow(args[0]);
        }, "p_form_invoice_apply_d.u_cnt_no");
      
        useDataIndexChange(async ({ args, instance }) => {
          console.log(`监听税收分类编码`);
          // console.log(`args`, args);
          $NG.execServer("getItm3TaxClasscode", { phid: args[0].u_ssfl_no }, function (res) {
            // console.log(res);
            if (res.count > 0) {
              const data = JSON.parse(res.data)[0].extendObjects; //单返回值
              // console.log(data);
              args[0].u_ssfl_name = data.class_name;
              args[0].u_ssfljc = data.class_spjm;
              args[0].u_yhzc = data.preferential;
              args[0].u_yhzclx = data.preferential_type;
              instance.updateRow(args[0]);
            } else {
              console.log("getItm3TaxClasscode 功能扩展暂无数据");
            }
          });
      
          if (args[0].u_ssfl_no === 4100) {
            args[0].u_pc_zs = 25;
            args[0].u_pc_zs_EXName = "13%税率的服务、不动产和无形资产";
          }
        }, "p_form_invoice_apply_d.u_ssfl_no");
      
        useDataIndexChange(async ({ args, instance }) => {
          console.log(`监听数量`);
          const record = args[0];
          record.qty ? record.qty : (record.qty = 1);
          record.amt = record.qty * record.prc;
          record.u_jshj = record.qty * record.u_vat_prc;
          record.u_ratee = record.u_jshj - record.amt;
          await Promise.all([
            getSumInvInfo(mstform, args[0]), // 发票信息更新
          ]);
          checkDgridData(args[0]);
          instance.updateRow(args[0]); // 更新界面
        }, "p_form_invoice_apply_d.qty");
      
        useDataIndexChange(async ({ args, instance }) => {
          console.log(`监听未税单价`);
          const record = args[0];
          record.qty ? record.qty : (record.qty = 1);
          record.taxrate ? record.taxrate : (record.taxrate = 0);
          record.amt = record.qty * record.prc;
          record.u_vat_prc = record.prc * (1 + record.taxrate);
          record.u_jshj = record.qty * record.u_vat_prc;
          record.u_ratee = record.u_jshj - record.amt;
          await Promise.all([
            getSumInvInfo(mstform, args[0]), // 发票信息更新
          ]);
          checkDgridData(args[0]);
          instance.updateRow(args[0]); // 更新界面
        }, "p_form_invoice_apply_d.prc");
      
        useDataIndexChange(async ({ args, instance }) => {
          console.log(`监听含税单价`);
          const record = args[0];
          record.qty ? record.qty : (record.qty = 1);
          record.taxrate ? record.taxrate : (record.taxrate = 0);
          record.u_jshj = record.qty * record.u_vat_prc;
          record.prc = record.u_vat_prc / (1 + record.taxrate);
          record.amt = record.qty * record.prc;
          record.u_ratee = record.u_jshj - record.amt;
          await Promise.all([
            getSumInvInfo(mstform, args[0]), // 发票信息更新
          ]);
          checkDgridData(args[0]);
          instance.updateRow(args[0]); // 更新界面
        }, "p_form_invoice_apply_d.u_vat_prc");
      
        useDataIndexChange(async ({ args, instance }) => {
          console.log(`监听未税金额`);
          const record = args[0];
          record.qty ? record.qty : (record.qty = 1);
          record.taxrate ? record.taxrate : (record.taxrate = 0);
          record.u_jshj = record.amt * (1 + record.taxrate);
          record.prc = record.amt / record.qty;
          record.u_vat_prc = record.prc * (1 + record.taxrate);
          record.u_ratee = record.u_jshj - record.amt;
          await Promise.all([
            getSumInvInfo(mstform, args[0]), // 发票信息更新
          ]);
          checkDgridData(args[0]);
          instance.updateRow(args[0]); // 更新界面
        }, "amt");
      
        useDataIndexChange(async ({ args, instance }) => {
          console.log(`监听含税金额`);
          const record = args[0];
          record.qty ? record.qty : (record.qty = 1);
          record.taxrate ? record.taxrate : (record.taxrate = 0);
          record.amt = record.u_jshj / (1 + record.taxrate);
          record.u_vat_prc = record.u_jshj / record.qty;
          record.prc = record.u_vat_prc / (1 + record.taxrate ?? 0);
          record.u_ratee = record.u_jshj - record.amt;
          await Promise.all([
            getSumInvInfo(mstform, args[0]), // 发票信息更新
          ]);
          checkDgridData(args[0]);
          instance.updateRow(args[0]); // 更新界面
        }, "u_jshj");
      
        useDataIndexChange(async ({ args, instance }) => {
          console.log(`监听税率`);
          const record = args[0];
          record.qty ? record.qty : (record.qty = 1);
          record.u_jshj ? record.u_jshj : (record.u_jshj = 0);
          record.u_vat_prc ? record.u_vat_prc : (record.u_vat_prc = 0);
          record.amt = record.u_jshj / (1 + record.taxrate ?? 0);
          record.prc = record.u_vat_prc / (1 + record.taxrate ?? 0);
          await Promise.all([
            getSumInvInfo(mstform, args[0]), // 发票信息更新
            getSumEqInfo(mstform, args[0]), // 设备信息更新
          ]);
          checkDgridData(args[0]);
          instance.updateRow(args[0]); // 更新界面
        }, "p_form_invoice_apply_d.taxrate");
      
        //根据合同id获取合同信息
        async function getCntMInfoByPhid(params) {
          $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt").getValue() }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            // // 触发自定义监听更改
            // MyEventObject.u_gfyh =  {
            //         //银行名称
            //         value: datas.tick_taxbankid,
            //         label: datas.tick_taxbankname,
            //     }
            // MyEventObject.u_xfyh = {
            //         //银行名称
            //         value: datas.inv_taxbankid,
            //         label: datas.inv_taxbankname,
            //     }
            //帮助字段赋值
            $NG.updateState((updater) => {
              console.log("获取和同数据", datas);
              updater.data.p_form_invoice_apply_m.setProps({
                u_cnt_amt: datas.cnt_sum_vat_fc,
                u_cnt_no: datas.pcm_no,
                //购方信息（客户信息）（收票单位信息）
                u_gfmc: {
                  //单位名称
                  value: datas.tick_id,
                  label: datas.tick_name,
                },
                u_gfbm: datas.tick_no, //单位编码
                u_gfsh: datas.tick_unisocialcredit, //社会信用代码
                u_gfdz: datas.tick_taxaddress, //单位地址
                u_gfdh: datas.tick_taxtelephone, //联系电话
                u_gfyh: {
                  //银行名称
                  value: datas.tick_taxbankid,
                  label: datas.tick_taxbankname,
                },
                u_gfyhzh: datas.tick_taxaccountno, //银行账号
                //销方信息（供应商信息）（开票单位信息）
                u_xfmc: {
                  //单位名称
                  value: datas.inv_id,
                  label: datas.inv_name,
                },
                inv_no: datas.inv_no, //单位编码
                u_xfsh: datas.inv_unisocialcredit, //社会信用代码
                u_xfdz: datas.inv_taxaddress, //单位地址
                u_xfdh: datas.inv_taxtelephone, //联系电话
                u_xfyh: {
                  //银行名称
                  value: datas.inv_taxbankid,
                  label: datas.inv_taxbankname,
                },
                u_xfyhzh: datas.inv_taxaccountno, //银行账号
                phid_fcur: {
                  value: datas.phid_fcur,
                  label: datas.phid_fcur_name,
                },
                exchangerate: datas.exch_rate,
              });
            });
          });
        }
        // 通过项目过滤合同号 初始化
        function cntMFilter() {
          if (!mstform) return;
          console.log(`正在过滤`);
          $NG.updateUI((updater, state) => {
            updater.fieldSetForm.p_form_invoice_apply_m.u_cnt.setProps({
              onBeforeOpen: async () => {
                var phid_pc = $NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue();
                console.log(`项目名：`, phid_pc);
                if (!phid_pc) {
                  $NG.alert("请先选择项目");
                  return false;
                } else {
                  return true;
                }
              },
              ...(!!$NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue() && {
                clientSqlFilter: {
                  bill_type: 1, //合同类型
                  phid_pc: $NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue(),
                },
              }),
            });
          });
        }
        async function getCntCount() {
          if (!mstform) return;
          console.log(`正在获取合同数量`);
          const phid = mstform.getItem("phid_pc").getValue();
          if (!phid) return;
          $NG.execServer("getCntCount", { type: 1, phid_pc: phid }, function (res) {
            console.log(res);
            if (res.count !== 0) {
              const _datas = JSON.parse(res.data);
              if (_datas.length === 1) {
                const _data = _datas[0].extendObjects;
                $NG.updateState((updater) => {
                  updater.data.p_form_invoice_apply_m.setProps({
                    u_cnt: {
                      label: _data.bill_name,
                      value: _data.phid,
                    },
                  });
                  setTimeout(() => {
                    cntDFilter();
                    if (page.oType == "add") {
                      getCntMInfoByPhid();
                    }
                  }, 200);
                });
              }
            }
          });
        }
      
        //计算本次申请含税/未税金额表头
        function sumAmt() {
          const _arr = dgrid.getRows();
          let _count = 0;
          let _count_vat = 0;
          _arr.forEach((item) => {
            _count += Number(item.amt) || 0;
            _count_vat += Number(item.u_jshj) || 0;
          });
          $NG.updateState((updater) => {
            updater.data.p_form_invoice_apply_m.setProps({
              u_amt_total_apply_vat: _count_vat,
              u_amt_total_apply: _count,
            });
          });
        }
      
        //新增部分合同详细
        //通过数量和单价计算金额
        function calculationPay() {
          const arr = ["p_form_invoice_apply_d.u_qty", "p_form_invoice_apply_d.u_vat_prc", "p_form_invoice_apply_d.v_amt"];
          arr.forEach((item, index) => {
            useDataIndexChange(({ args, instance }) => {
              console.log(`监听----${item}`, args);
              args[0].u_amt = (args[0].u_qty || 0) * args[0].u_vat_prc || 0;
              instance.updateRow(args[0]);
            }, item);
          });
        }
        // 获取银行行号
        //根据银行主键获取银行信息
        function GetBankInfoByPhid(phid, str) {
          const mstform = $NG.getCmpApi("p_form_invoice_apply_m");
          console.log(`检查传入的参数`, phid, str);
          if (!phid || !str) return;
          $NG.execServer("GetBankInfoByPhid", { phid: phid }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            // console.log(datas);
            if (str == "gf") {
              mstform.getItem("u_gfhh").setValue(datas.bankno);
              console.log(`购方行号：`, datas.bankno);
            } else if (str == "xf") {
              mstform.getItem("u_xfhh").setValue(datas.bankno);
            }
          });
        }
        // 格式化日期
        function formatDate(dateStr, outputFormat) {
          const date = new Date(dateStr);
      
          if (isNaN(date)) {
            return "无效的日期字符串";
          }
      
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, "0");
          const day = String(date.getDate()).padStart(2, "0");
          const hours = String(date.getHours()).padStart(2, "0");
          const minutes = String(date.getMinutes()).padStart(2, "0");
      
          let formattedDate;
      
          switch (outputFormat) {
            case "yyyy-mm-dd":
              formattedDate = `${year}-${month}-${day}`;
              break;
            case "yyyy-mm-dd HH:mm":
              formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
              break;
            case "yyyy-mm":
              formattedDate = `${year}-${month}`;
              break;
            // 可以根据需要继续添加其他格式的处理逻辑
            default:
              formattedDate = "不支持的输出格式";
          }
      
          return formattedDate;
        }
      });
      
      // 获取项目
      function getProjectInfo(mstform) {
        console.log(`getPtInfoByPhid`);
        const phid = mstform.getItem("phid_pc")?.getValue();
        if (!phid) return;
        try {
          $NG.execServer("getPtInfoByPhid", { phid: phid }, (res) => {
            if (res.count == 0) return;
            const _data = JSON.parse(res.data)[0].extendObjects;
            const isYesNoText = (value) => (value === "1" ? "是" : "否");
            $NG.updateState((updater) => {
              updater.data.p_form_invoice_apply_m.setProps({
                u_pc_no: _data.pc_no, //项目编码
                u_pc_no: _data.pc_no, //项目编码
                //事业部or组织
                phid_org: {
                  value: _data.org_phid,
                  label: _data.org_name,
                },
                phid_emp: {
                  label: _data.project_manager_name,
                  value: _data.project_manager_phid,
                },
                //售前顾问
                u_sqgw: {
                  value: _data.user_sqgw_phid,
                  label: _data.user_sqgw_name,
                },
                //区域中心
                u_regional_center: {
                  value: _data.regional_center_phid,
                  label: _data.regional_center_name,
                },
                //产品线
                u_product_line: {
                  value: _data.midwife_phid,
                  label: _data.midwife_name,
                },
                //部门
                u_dept: {
                  value: _data.dept_phid,
                  label: _data.dept_name,
                },
                //项目类型
                u_pc_type: {
                  value: _data.type_phid,
                  label: _data.type_name,
                },
                u_sfqf: { value: _data.user_sf_qf, label: isYesNoText(_data.user_sf_qf) }, // 这里将数值转换为文本描述
              });
            });
          });
        } catch (err) {
          $NG.alert("获取项目信息发生失败请检查~");
        }
      }
      
      // 获取企业信息
      function getEnterpriseInfoByPhid(mstform) {
          // 禁用
          return
        console.log("getEnterpriseInfoByPhid");
        const phid_org = mstform.getItem("phid_org");
        if (!phid_org) return;
      
        const phidValue = phid_org.getValue();
        if (!phidValue) return console.warn("phid_org 为空，无法获取企业信息");
      
        $NG.execServer("getEnterpriseInfoByPhid", { phid: phidValue }, (res) => {
          if (res.count == 0) return;
          try {
            const datas = JSON.parse(res.data)[0].extendObjects;
            if (!datas) return;
            // console.log("组织信息", datas);
            $NG.updateState((updater) => {
              updater.data.p_form_invoice_apply_m.setProps({
                u_xfmc: datas.compname,
                u_xfsh: datas.unisocialcredit,
                u_xfdz: datas.taxaddress,
                u_xfdh: datas.taxtelephone,
                u_xfyhzh: datas.bankno,
                u_xfyh: datas.taxbankname,
                u_xfhh: datas.taxaccountno,
              });
            });
          } catch (error) {
            console.error("解析企业信息出错", error);
          }
        });
      }
      // 获取供应商信息（销房）
      function searchGys(phid){
          if(!phid) return 
          $NG.execServer("searchGys",{phid},(res)=>{
              if(res.count == 0) return
              const _data = JSON.parse(res.data)[0].extendObjects
              $NG.updaterUI((updater)=>{
                  updater.data.p_form_invoice_apply_m.setProps({
                      u_xfsh:_data.taxaccountno,
                      u_xfdz:_data.user_zc_address,
                      u_xfdh:_data.taxtelephone,
                      u_xfhh:_data.user_yhhh,
                      u_xfyh:{
                          label:_data.taxbankname,
                          value:_data.taxbank_id
                      },
                      u_xfyhzh:_data.user_yhzhmc
                  })
              })
          })
      }
      
      //按照项目和税率获取累计开票金额
      async function getSumInvInfo(mstform, record) {
        console.log(`getSumInvInfo`);
        const phid = mstform.getItem("phid")?.getValue() ?? 0;
        const phid_pc = mstform.getItem("phid_pc")?.getValue();
        const taxrate = record.taxrate ?? 0;
        let data = {};
        if (!phid_pc) return;
        const res = await new Promise((resolve) => $NG.execServer("getSumInvInfo", { phid_pc: phid_pc, taxrate: taxrate, phid: phid }, resolve));
        try {
          data = res.count > 0 ? JSON.parse(res.data)?.[0]?.extendObjects : {};
        } catch (error) {
          console.error("getSumInvInfo", error);
        }
        record.u_total_inv_amt = data.amt ?? 0;
        record.u_total_inv_amt_vat = data.amt_vat ?? 0;
      }
      //按照项目和税率获取设备清单金额
      async function getSumEqInfo(mstform, record) {
        console.log(`getSumEqInfo`);
        const phid_pc = mstform.getItem("phid_pc")?.getValue();
        const taxrate = record.taxrate ?? 0;
        let data = {};
      
        if (!phid_pc) return;
        const res = await new Promise((resolve) => $NG.execServer("getSumEqInfo", { phid_pc: phid_pc, taxrate: taxrate }, resolve));
        try {
          data = res.count > 0 ? JSON.parse(res.data)?.[0]?.extendObjects : {};
        } catch (error) {
          console.error("getSumEqInfo", error);
        }
        record.u_total_eq_amt = data.amt ?? 0;
        record.u_total_eq_amt_vat = data.amt_vat ?? 0;
      }
      // 检查数据是否超过设备清单金额
      async function checkDgridData(record) {
        console.log(`checkDgridData`);
        const mstform = $NG.getCmpApi("p_form_invoice_apply_m");
        const dgrid = $NG.getCmpApi("p_form_invoice_apply_d");
        const dStore = dgrid.getStore();
        const dStoreData = dStore.data;
      
        let total = 0;
        // 使用 for 循环代替 forEach，以便在条件成立时直接退出函数
        for (let item of dStoreData) {
          if (String(record.taxrate) === String(item.taxrate)) {
            total += parseFloat(item.u_jshj) || 0; // 更严格地转换金额
            // console.log(total);
            if (total + record.u_total_inv_amt_vat > record.u_total_eq_amt_vat) {
              // 弹出警告并终止后续计算
              $NG.message(`税率为 ${record.taxrate} 累计开票金额 ${total + record.u_total_inv_amt_vat} 超出设备清单金额 ${record.u_total_eq_amt_vat}`);
              record.amt = 0;
              record.u_jshj = 0;
              record.prc = 0;
              record.u_vat_prc = 0;
              return; // 终止函数执行
            }
          }
        }
      }
      
      function mstformUpdateUI(mstform) {
        console.log("mstformUpdateUI");
        mstform.getItem("u_hllx").setValue({
          value: "1",
          label: "蓝字发票",
        });
      }
      
      function dgrid1UpdateUI(params) {
        const commonHideArray = ["u_total_eq_amt", "u_total_inv_amt"];
        commonHideArray.forEach((item) => {
          $NG.updateUI((updater) => {
            if (updater.editGrid.p_form_invoice_apply_d[item]) {
              updater.editGrid.p_form_invoice_apply_d[item].setProps({
                hidden: true, // 隐藏
              });
            }
          });
        });
      }
      
      function cntDFilter() {
        $NG.updateUI((updater) =>
          updater.editGrid.p_form_invoice_apply_d.u_cnt_no.setProps((p) => {
            return {
              ...p,
              editor: {
                ...p.editor,
                clientSqlFilter: {
                  pphid: $NG.getCmpApi("p_form_invoice_apply_m").getItem("u_cnt").getValue() || 0,
                },
              },
            };
          })
        );
      }
      
      async function getCntDInfoByPhid(mstform, record) {
        console.log("getCntDInfoByPhid");
      
        try {
          const cndId = mstform.getItem("u_cnt")?.getValue();
          const phid = record.u_cnt_no;
      
          const res = await new Promise((resolve) => $NG.execServer("getCntDInfoByPhid", { cnd_id: cndId, phid }, resolve));
      
          console.log(res);
      
          if (res.count > 0 && res.data) {
            const parsed = JSON.parse(res.data);
            const data = parsed[0]?.extendObjects;
      
            if (data) {
              console.log(data);
              record.u_cnt_name = data.item_name || ""; // 合同清单编码
              record.u_ggxh = data.user_ggxh || ""; // 规格型号
              record.u_msunit = data.unit_phid || "";
              record.u_msunit_EXName = data.unit_name || ""; // 计量单位
              record.qty = data.qty || 0; // 数量
              record.taxrate = data.taxrate || 0; // 税率
              record.prc = data.prc_fc || 0; // 未税单价
              record.u_vat_prc = data.prc_vat_fc || 0; // 含税单价
              record.amt = data.amt_fc || 0; // 未税金额
              record.u_jshj = data.amt_vat_fc || 0; // 含税金额
              record.u_ratee = record.u_jshj - record.amt; // 税额
            } else {
              console.warn("extendObjects 数据为空");
            }
          } else {
            console.log("功能扩展暂无数据");
          }
        } catch (error) {
          console.error("getCntDInfoByPhid 异常：", error);
        }
      }
      
    }, 600);
    // 默认数量为1
    // args[0].forEach((item) => {
    //   if (!item.qty || item.qty < 0) {
    //     item.qty = 1;
    //   }
    // });

    // 遍历明细，如果明细存在建筑服务的税收分类编码，更改主表字段属性

    const fields = ["u_tdyw", "u_tdzzs_no", "u_jzfwfsd", "u_detail_addr", "u_kdbz"];
    let isRequired = false;
    let filter = "itm3_tax_classcode.phid != 0"; // 默认值

    _data.forEach(async (item) => {
      await getSumEqInfo(mstform, item);
      dgrid.refreshView();
    });

    _data.forEach((item) => {
      if (item.u_ssfl_no === 4100) {
        isRequired = true;
      }
      if(!item.u_kp_remark){
        item.u_kp_remark = '无'
      }
    });

    if (_data.some((item) => item.u_ssfl_no === 4100)) {
      filter = "itm3_tax_classcode.phid = 4100";
    } else if (_data.some((item) => item.u_ssfl_no !== "" && item.u_ssfl_no !== null && item.u_ssfl_no !== undefined)) {
      if (args[0].u_ssfl_no !== 4100) {
        filter = "itm3_tax_classcode.phid != 4100";
      }
    }

    $NG.updateUI((updater) => {
      const ssflField = updater.editGrid.p_form_invoice_apply_d.u_ssfl_no;
      if (ssflField) {
        ssflField.setProps({ clientSqlFilter: filter });
      }
    });
    $NG.updateUI((updater) => {
      fields.forEach((field) => {
        updater.fieldSetForm.p_form_invoice_apply_m[field].setProps({
          required: isRequired,
          hidden: !isRequired,
        });
      });
    });
    if (!mstform.getItem("u_tdyw").getValue()) {
      mstform.getItem("u_tdyw").setValue({
        value: "E03",
        label: "建筑服务",
      });
    }

    dgrid.refreshView();
  }, "p_form_invoice_apply_d");

  //优先性设置
  // let _d_amt = 0;
  // useUpdateRow(({ args }) => {
  //   console.log(args);
  //   const record = args[0];
  //   const _data = args[0];
  //   record.u_ratee = record.u_jshj - record.amt;
  //   if (_data.u_vat_prc && _data.taxrate) {
  //     _data.prc = Number(_data.u_vat_prc) / (1 + Number(_data.taxrate));
  //   }
  //   if (_data.u_jshj && _data.taxrate) {
  //     _data.amt = Number(_data.u_jshj) / (1 + Number(_data.taxrate));
  //     _data.u_ratee = Number((_data.u_jshj / (1 + _data.taxrate)) * _data.taxrate);
  //   }
  //   dgrid.refreshView();
  // }, "p_form_invoice_apply_d");

  useDataIndexChange(async ({ args, instance }) => {
    console.log(`监听 u_cnt_no`);
    await getCntDInfoByPhid(mstform, args[0]);
    await getSumEqInfo(mstform, args[0]); // 等 getCntDInfoByPhid 执行完成之后再执行
    instance.updateRow(args[0]);
  }, "p_form_invoice_apply_d.u_cnt_no");

  useDataIndexChange(async ({ args, instance }) => {
    console.log(`监听税收分类编码`);
    // console.log(`args`, args);
    $NG.execServer("getItm3TaxClasscode", { phid: args[0].u_ssfl_no }, function (res) {
      // console.log(res);
      if (res.count > 0) {
        const data = JSON.parse(res.data)[0].extendObjects; //单返回值
        // console.log(data);
        args[0].u_ssfl_name = data.class_name;
        args[0].u_ssfljc = data.class_spjm;
        args[0].u_yhzc = data.preferential;
        args[0].u_yhzclx = data.preferential_type;
        instance.updateRow(args[0]);
      } else {
        console.log("getItm3TaxClasscode 功能扩展暂无数据");
      }
    });

    if (args[0].u_ssfl_no === 4100) {
      args[0].u_pc_zs = 25;
      args[0].u_pc_zs_EXName = "13%税率的服务、不动产和无形资产";
    }
  }, "p_form_invoice_apply_d.u_ssfl_no");

  useDataIndexChange(async ({ args, instance }) => {
    console.log(`监听数量`);
    const record = args[0];
    record.qty ? record.qty : (record.qty = 1);
    record.amt = record.qty * record.prc;
    record.u_jshj = record.qty * record.u_vat_prc;
    record.u_ratee = record.u_jshj - record.amt;
    await Promise.all([
      getSumInvInfo(mstform, args[0]), // 发票信息更新
    ]);
    checkDgridData(args[0]);
    instance.updateRow(args[0]); // 更新界面
  }, "p_form_invoice_apply_d.qty");

  useDataIndexChange(async ({ args, instance }) => {
    console.log(`监听未税单价`);
    const record = args[0];
    record.qty ? record.qty : (record.qty = 1);
    record.taxrate ? record.taxrate : (record.taxrate = 0);
    record.amt = record.qty * record.prc;
    record.u_vat_prc = record.prc * (1 + record.taxrate);
    record.u_jshj = record.qty * record.u_vat_prc;
    record.u_ratee = record.u_jshj - record.amt;
    await Promise.all([
      getSumInvInfo(mstform, args[0]), // 发票信息更新
    ]);
    checkDgridData(args[0]);
    instance.updateRow(args[0]); // 更新界面
  }, "p_form_invoice_apply_d.prc");

  useDataIndexChange(async ({ args, instance }) => {
    console.log(`监听含税单价`);
    const record = args[0];
    record.qty ? record.qty : (record.qty = 1);
    record.taxrate ? record.taxrate : (record.taxrate = 0);
    record.u_jshj = record.qty * record.u_vat_prc;
    record.prc = record.u_vat_prc / (1 + record.taxrate);
    record.amt = record.qty * record.prc;
    record.u_ratee = record.u_jshj - record.amt;
    await Promise.all([
      getSumInvInfo(mstform, args[0]), // 发票信息更新
    ]);
    checkDgridData(args[0]);
    instance.updateRow(args[0]); // 更新界面
  }, "p_form_invoice_apply_d.u_vat_prc");

  useDataIndexChange(async ({ args, instance }) => {
    console.log(`监听未税金额`);
    const record = args[0];
    record.qty ? record.qty : (record.qty = 1);
    record.taxrate ? record.taxrate : (record.taxrate = 0);
    record.u_jshj = record.amt * (1 + record.taxrate);
    record.prc = record.amt / record.qty;
    record.u_vat_prc = record.prc * (1 + record.taxrate);
    record.u_ratee = record.u_jshj - record.amt;
    await Promise.all([
      getSumInvInfo(mstform, args[0]), // 发票信息更新
    ]);
    checkDgridData(args[0]);
    instance.updateRow(args[0]); // 更新界面
  }, "amt");

  useDataIndexChange(async ({ args, instance }) => {
    console.log(`监听含税金额`);
    const record = args[0];
    record.qty ? record.qty : (record.qty = 1);
    record.taxrate ? record.taxrate : (record.taxrate = 0);
    record.amt = record.u_jshj / (1 + record.taxrate);
    record.u_vat_prc = record.u_jshj / record.qty;
    record.prc = record.u_vat_prc / (1 + record.taxrate ?? 0);
    record.u_ratee = record.u_jshj - record.amt;
    await Promise.all([
      getSumInvInfo(mstform, args[0]), // 发票信息更新
    ]);
    checkDgridData(args[0]);
    instance.updateRow(args[0]); // 更新界面
  }, "u_jshj");

  useDataIndexChange(async ({ args, instance }) => {
    console.log(`监听税率`);
    const record = args[0];
    record.qty ? record.qty : (record.qty = 1);
    record.u_jshj ? record.u_jshj : (record.u_jshj = 0);
    record.u_vat_prc ? record.u_vat_prc : (record.u_vat_prc = 0);
    record.amt = record.u_jshj / (1 + record.taxrate ?? 0);
    record.prc = record.u_vat_prc / (1 + record.taxrate ?? 0);
    await Promise.all([
      getSumInvInfo(mstform, args[0]), // 发票信息更新
      getSumEqInfo(mstform, args[0]), // 设备信息更新
    ]);
    checkDgridData(args[0]);
    instance.updateRow(args[0]); // 更新界面
  }, "p_form_invoice_apply_d.taxrate");

  //根据合同id获取合同信息
  async function getCntMInfoByPhid(params) {
    $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt").getValue() }, function (res) {
      const datas = JSON.parse(res.data)[0].extendObjects;
      // // 触发自定义监听更改
      // MyEventObject.u_gfyh =  {
      //         //银行名称
      //         value: datas.tick_taxbankid,
      //         label: datas.tick_taxbankname,
      //     }
      // MyEventObject.u_xfyh = {
      //         //银行名称
      //         value: datas.inv_taxbankid,
      //         label: datas.inv_taxbankname,
      //     }
      //帮助字段赋值
      $NG.updateState((updater) => {
        console.log("获取和同数据", datas);
        updater.data.p_form_invoice_apply_m.setProps({
          u_cnt_amt: datas.cnt_sum_vat_fc,
          u_cnt_no: datas.pcm_no,
          //购方信息（客户信息）（收票单位信息）
          u_gfmc: {
            //单位名称
            value: datas.tick_id,
            label: datas.tick_name,
          },
          u_gfbm: datas.tick_no, //单位编码
          u_gfsh: datas.tick_unisocialcredit, //社会信用代码
          u_gfdz: datas.tick_taxaddress, //单位地址
          u_gfdh: datas.tick_taxtelephone, //联系电话
          u_gfyh: {
            //银行名称
            value: datas.tick_taxbankid,
            label: datas.tick_taxbankname,
          },
          u_gfyhzh: datas.tick_taxaccountno, //银行账号
          //销方信息（供应商信息）（开票单位信息）
          u_xfmc: {
            //单位名称
            value: datas.inv_id,
            label: datas.inv_name,
          },
          inv_no: datas.inv_no, //单位编码
          u_xfsh: datas.inv_unisocialcredit, //社会信用代码
          u_xfdz: datas.inv_taxaddress, //单位地址
          u_xfdh: datas.inv_taxtelephone, //联系电话
          u_xfyh: {
            //银行名称
            value: datas.inv_taxbankid,
            label: datas.inv_taxbankname,
          },
          u_xfyhzh: datas.inv_taxaccountno, //银行账号
          phid_fcur: {
            value: datas.phid_fcur,
            label: datas.phid_fcur_name,
          },
          exchangerate: datas.exch_rate,
        });
      });
    });
  }
  // 通过项目过滤合同号 初始化
  function cntMFilter() {
    if (!mstform) return;
    console.log(`正在过滤`);
    $NG.updateUI((updater, state) => {
      updater.fieldSetForm.p_form_invoice_apply_m.u_cnt.setProps({
        onBeforeOpen: async () => {
          var phid_pc = $NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue();
          console.log(`项目名：`, phid_pc);
          if (!phid_pc) {
            $NG.alert("请先选择项目");
            return false;
          } else {
            return true;
          }
        },
        ...(!!$NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue() && {
          clientSqlFilter: {
            bill_type: 1, //合同类型
            phid_pc: $NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue(),
          },
        }),
      });
    });
  }
  async function getCntCount() {
    if (!mstform) return;
    console.log(`正在获取合同数量`);
    const phid = mstform.getItem("phid_pc").getValue();
    if (!phid) return;
    $NG.execServer("getCntCount", { type: 1, phid_pc: phid }, function (res) {
      console.log(res);
      if (res.count !== 0) {
        const _datas = JSON.parse(res.data);
        if (_datas.length === 1) {
          const _data = _datas[0].extendObjects;
          $NG.updateState((updater) => {
            updater.data.p_form_invoice_apply_m.setProps({
              u_cnt: {
                label: _data.bill_name,
                value: _data.phid,
              },
            });
            setTimeout(() => {
              cntDFilter();
              if (page.oType == "add") {
                getCntMInfoByPhid();
              }
            }, 200);
          });
        }
      }
    });
  }

  //计算本次申请含税/未税金额表头
  function sumAmt() {
    const _arr = dgrid.getRows();
    let _count = 0;
    let _count_vat = 0;
    _arr.forEach((item) => {
      _count += Number(item.amt) || 0;
      _count_vat += Number(item.u_jshj) || 0;
    });
    $NG.updateState((updater) => {
      updater.data.p_form_invoice_apply_m.setProps({
        u_amt_total_apply_vat: _count_vat,
        u_amt_total_apply: _count,
      });
    });
  }

  //新增部分合同详细
  //通过数量和单价计算金额
  function calculationPay() {
    const arr = ["p_form_invoice_apply_d.u_qty", "p_form_invoice_apply_d.u_vat_prc", "p_form_invoice_apply_d.v_amt"];
    arr.forEach((item, index) => {
      useDataIndexChange(({ args, instance }) => {
        console.log(`监听----${item}`, args);
        args[0].u_amt = (args[0].u_qty || 0) * args[0].u_vat_prc || 0;
        instance.updateRow(args[0]);
      }, item);
    });
  }
  // 获取银行行号
  //根据银行主键获取银行信息
  function GetBankInfoByPhid(phid, str) {
    const mstform = $NG.getCmpApi("p_form_invoice_apply_m");
    console.log(`检查传入的参数`, phid, str);
    if (!phid || !str) return;
    $NG.execServer("GetBankInfoByPhid", { phid: phid }, function (res) {
      const datas = JSON.parse(res.data)[0].extendObjects;
      // console.log(datas);
      if (str == "gf") {
        mstform.getItem("u_gfhh").setValue(datas.bankno);
        console.log(`购方行号：`, datas.bankno);
      } else if (str == "xf") {
        mstform.getItem("u_xfhh").setValue(datas.bankno);
      }
    });
  }
  function sumAmountBeforeDate(dataList, targetDateStr) {
    const targetDate = new Date(targetDateStr);
  
    return dataList.reduce((sum, item) => {
      const itemDate = new Date(item.u_receivable_dt);
      if (itemDate <= targetDate) {
        return sum + Number(item.u_payable_amt);
      }
      return sum;
    }, 0);
  }
  //获取 里程碑计划回款明细金额
  getLcbHkInfo()
  async function getLcbHkInfo(){
    const phid_pc = mstform.getItem("phid_pc").getValue();
    if(!phid_pc){return;}
    await $NG.execServer("getLcbHkInfo",{phid_pc},(res)=>{
        console.log(`里程碑计划`,res);
        if(res.count == 0) return 
        const _data = JSON.parse(res.data).reduce((value,item)=>{
            value.push({...item.extendObjects})
            return value
        },[])
        $NG.updateState((updater)=>{
            updater.data.p_form_invoice_apply_m.setProps({
                u_yskje:sumAmountBeforeDate(_data)
            })
        })
    })
  }
  // 格式化日期
  function formatDate(dateStr, outputFormat) {
    const date = new Date(dateStr);

    if (isNaN(date)) {
      return "无效的日期字符串";
    }

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");

    let formattedDate;

    switch (outputFormat) {
      case "yyyy-mm-dd":
        formattedDate = `${year}-${month}-${day}`;
        break;
      case "yyyy-mm-dd HH:mm":
        formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
        break;
      case "yyyy-mm":
        formattedDate = `${year}-${month}`;
        break;
      // 可以根据需要继续添加其他格式的处理逻辑
      default:
        formattedDate = "不支持的输出格式";
    }

    return formattedDate;
  }
});

// 获取项目
function getProjectInfo(mstform) {
  console.log(`getPtInfoByPhid`);
  const phid = mstform.getItem("phid_pc")?.getValue();
  if (!phid) return;
  try {
    $NG.execServer("getPtInfoByPhid", { phid: phid }, (res) => {
      if (res.count == 0) return;
      const _data = JSON.parse(res.data)[0].extendObjects;
      const isYesNoText = (value) => (value === "1" ? "是" : "否");
      $NG.updateState((updater) => {
        updater.data.p_form_invoice_apply_m.setProps({
          u_pc_no: _data.pc_no, //项目编码
          u_pc_no: _data.pc_no, //项目编码
          //事业部or组织
          phid_org: {
            value: _data.org_phid,
            label: _data.org_name,
          },
          phid_emp: {
            label: _data.project_manager_name,
            value: _data.project_manager_phid,
          },
          //售前顾问
          u_sqgw: {
            value: _data.user_sqgw_phid,
            label: _data.user_sqgw_name,
          },
          //区域中心
          u_regional_center: {
            value: _data.regional_center_phid,
            label: _data.regional_center_name,
          },
          //产品线
          u_product_line: {
            value: _data.midwife_phid,
            label: _data.midwife_name,
          },
          //部门
          u_dept: {
            value: _data.dept_phid,
            label: _data.dept_name,
          },
          //项目类型
          u_pc_type: {
            value: _data.type_phid,
            label: _data.type_name,
          },
          u_sfqf: { value: _data.user_sf_qf, label: isYesNoText(_data.user_sf_qf) }, // 这里将数值转换为文本描述
        });
      });
    });
  } catch (err) {
    $NG.alert("获取项目信息发生失败请检查~");
  }
}

// 获取企业信息
function getEnterpriseInfoByPhid(mstform) {
    // 禁用
    return
  console.log("getEnterpriseInfoByPhid");
  const phid_org = mstform.getItem("phid_org");
  if (!phid_org) return;

  const phidValue = phid_org.getValue();
  if (!phidValue) return console.warn("phid_org 为空，无法获取企业信息");

  $NG.execServer("getEnterpriseInfoByPhid", { phid: phidValue }, (res) => {
    if (res.count == 0) return;
    try {
      const datas = JSON.parse(res.data)[0].extendObjects;
      if (!datas) return;
      // console.log("组织信息", datas);
      $NG.updateState((updater) => {
        updater.data.p_form_invoice_apply_m.setProps({
          u_xfmc: datas.compname,
          u_xfsh: datas.unisocialcredit,
          u_xfdz: datas.taxaddress,
          u_xfdh: datas.taxtelephone,
          u_xfyhzh: datas.bankno,
          u_xfyh: datas.taxbankname,
          u_xfhh: datas.taxaccountno,
        });
      });
    } catch (error) {
      console.error("解析企业信息出错", error);
    }
  });
}
// 获取供应商信息（销房）
function searchGys(phid){
    if(!phid) return 
    $NG.execServer("searchGys",{phid},(res)=>{
        if(res.count == 0) return
        const _data = JSON.parse(res.data)[0].extendObjects
        $NG.updaterUI((updater)=>{
            updater.data.p_form_invoice_apply_m.setProps({
                u_xfsh:_data.taxaccountno,
                u_xfdz:_data.user_zc_address,
                u_xfdh:_data.taxtelephone,
                u_xfhh:_data.user_yhhh,
                u_xfyh:{
                    label:_data.taxbankname,
                    value:_data.taxbank_id
                },
                u_xfyhzh:_data.user_yhzhmc
            })
        })
    })
}

//按照项目和税率获取累计开票金额
async function getSumInvInfo(mstform, record) {
  console.log(`getSumInvInfo`);
  const phid = mstform.getItem("phid")?.getValue() ?? 0;
  const phid_pc = mstform.getItem("phid_pc")?.getValue();
  const taxrate = record.taxrate ?? 0;
  let data = {};
  if (!phid_pc) return;
  const res = await new Promise((resolve) => $NG.execServer("getSumInvInfo", { phid_pc: phid_pc, taxrate: taxrate, phid: phid }, resolve));
  try {
    data = res.count > 0 ? JSON.parse(res.data)?.[0]?.extendObjects : {};
  } catch (error) {
    console.error("getSumInvInfo", error);
  }
  record.u_total_inv_amt = data.amt ?? 0;
  record.u_total_inv_amt_vat = data.amt_vat ?? 0;
}
//按照项目和税率获取设备清单金额
async function getSumEqInfo(mstform, record) {
  console.log(`getSumEqInfo`);
  const phid_pc = mstform.getItem("phid_pc")?.getValue();
  const taxrate = record.taxrate ?? 0;
  let data = {};

  if (!phid_pc) return;
  const res = await new Promise((resolve) => $NG.execServer("getSumEqInfo", { phid_pc: phid_pc, taxrate: taxrate }, resolve));
  try {
    data = res.count > 0 ? JSON.parse(res.data)?.[0]?.extendObjects : {};
  } catch (error) {
    console.error("getSumEqInfo", error);
  }
  record.u_total_eq_amt = data.amt ?? 0;
  record.u_total_eq_amt_vat = data.amt_vat ?? 0;
}
// 检查数据是否超过设备清单金额
async function checkDgridData(record) {
  console.log(`checkDgridData`);
  const mstform = $NG.getCmpApi("p_form_invoice_apply_m");
  const dgrid = $NG.getCmpApi("p_form_invoice_apply_d");
  const dStore = dgrid.getStore();
  const dStoreData = dStore.data;

  let total = 0;
  // 使用 for 循环代替 forEach，以便在条件成立时直接退出函数
  for (let item of dStoreData) {
    if (String(record.taxrate) === String(item.taxrate)) {
      total += parseFloat(item.u_jshj) || 0; // 更严格地转换金额
      // console.log(total);
      if (total + record.u_total_inv_amt_vat > record.u_total_eq_amt_vat) {
        // 弹出警告并终止后续计算
        $NG.message(`税率为 ${record.taxrate} 累计开票金额 ${total + record.u_total_inv_amt_vat} 超出设备清单金额 ${record.u_total_eq_amt_vat}`);
        record.amt = 0;
        record.u_jshj = 0;
        record.prc = 0;
        record.u_vat_prc = 0;
        return; // 终止函数执行
      }
    }
  }
}

function mstformUpdateUI(mstform) {
  console.log("mstformUpdateUI");
  mstform.getItem("u_hllx").setValue({
    value: "1",
    label: "蓝字发票",
  });
}

function dgrid1UpdateUI(params) {
  const commonHideArray = ["u_total_eq_amt", "u_total_inv_amt"];
  commonHideArray.forEach((item) => {
    $NG.updateUI((updater) => {
      if (updater.editGrid.p_form_invoice_apply_d[item]) {
        updater.editGrid.p_form_invoice_apply_d[item].setProps({
          hidden: true, // 隐藏
        });
      }
    });
  });
}

function cntDFilter() {
  $NG.updateUI((updater) =>
    updater.editGrid.p_form_invoice_apply_d.u_cnt_no.setProps((p) => {
      return {
        ...p,
        editor: {
          ...p.editor,
          clientSqlFilter: {
            pphid: $NG.getCmpApi("p_form_invoice_apply_m").getItem("u_cnt").getValue() || 0,
          },
        },
      };
    })
  );
}

async function getCntDInfoByPhid(mstform, record) {
  console.log("getCntDInfoByPhid");

  try {
    const cndId = mstform.getItem("u_cnt")?.getValue();
    const phid = record.u_cnt_no;

    const res = await new Promise((resolve) => $NG.execServer("getCntDInfoByPhid", { cnd_id: cndId, phid }, resolve));

    console.log(res);

    if (res.count > 0 && res.data) {
      const parsed = JSON.parse(res.data);
      const data = parsed[0]?.extendObjects;

      if (data) {
        console.log(data);
        record.u_cnt_name = data.item_name || ""; // 合同清单编码
        record.u_ggxh = data.user_ggxh || ""; // 规格型号
        record.u_msunit = data.unit_phid || "";
        record.u_msunit_EXName = data.unit_name || ""; // 计量单位
        record.qty = data.qty || 0; // 数量
        record.taxrate = data.taxrate || 0; // 税率
        record.prc = data.prc_fc || 0; // 未税单价
        record.u_vat_prc = data.prc_vat_fc || 0; // 含税单价
        record.amt = data.amt_fc || 0; // 未税金额
        record.u_jshj = data.amt_vat_fc || 0; // 含税金额
        record.u_ratee = record.u_jshj - record.amt; // 税额
      } else {
        console.warn("extendObjects 数据为空");
      }
    } else {
      console.log("功能扩展暂无数据");
    }
  } catch (error) {
    console.error("getCntDInfoByPhid 异常：", error);
  }
}
